import 'dart:async';
import 'dart:math';

import 'package:get/get.dart';
import 'package:number_spark_flutter/config/ns_base_controller.dart';
import 'package:number_spark_flutter/db_manager/bean/ns_record_bean.dart';
import 'package:number_spark_flutter/routes/ns_app_pages.dart';
import 'package:number_spark_flutter/utils/ns_db_utils.dart';
import 'package:number_spark_flutter/utils/ns_user_utils.dart';

import 'view/single_correct_dialog.dart';

class Question {
  final String expression;
  final List<int> options;
  final int answer;
  int myAnswer = -1;
  int yourAnswer = -1;
  final int correctIndex;

  Question({required this.expression, required this.options, required this.answer, required this.correctIndex});
}

const String idCountDown = 'countDown';
const String idQuestion = 'question';

class NSSingleLogic extends NSBaseController {
  Timer? _timer;
  int countDown = 60;
  late Question question;

  List<Question> questionsList = [];

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
    NSDBUtils.instance.daoRecord.insert([
      NSRecordBean(
        type: 'single',
        myCorrectCount: questionsList.where((element) => element.myAnswer == element.answer).length,
        userId: NSUserUtils.getId(),
      )
    ]);
  }

  @override
  void onInit() {
    super.onInit();
    question = generateQuestion();
    onStartTimer();
  }

  onStartTimer() {
    _timer ??= Timer.periodic(const Duration(seconds: 1), (timer) {
      countDown--;
      if (countDown == 0) {
        _timer?.cancel();
        _timer = null;
        onShowCorrectDialog();
      }
      update([idCountDown]);
    });
  }

  doClickOption(int answer) {
    question.myAnswer = answer;
    questionsList.add(question);
    onNextQuestion();
  }

  onShowCorrectDialog() {
    Get.dialog(SingleCorrectDialog(
      correctAnswer: questionsList.where((element) => element.myAnswer == element.answer).length.toString(),
      onClickOk: () {
        Get.until((route) => route.settings.name == NSRoutes.main);
      },
    ));
  }

  onNextQuestion() {
    question = generateQuestion();
    update([idQuestion]);
  }
}
